package com.wanban.download.model

import android.net.Uri
import android.text.TextUtils
import java.util.Locale

/**
 * 不能随意删除字段，否则打包会出问题
 */
class Ts {
    var url: String? = null //分片url
    var index: Int = 0 //分片索引值,第一个为0
    var tsSize: Long = 0 //分片大小
    var complete: Boolean = false // ts是否已下载完成
    var keyIV: String? = null
    var method: String? = null
    var keyUri: String? = null
    // 下载重试次数
    var retryTimes = 0
    // 是否正在重试
    var isRetrying = false

    fun initTsAttributes(url: String, index: Int) {
        this.url = url
        this.index = index
    }

    fun setKeyConfig(method: String?, keyUri: String?, keyIV: String?) {
        this.method = method
        this.keyUri = keyUri
        this.keyIV = keyIV
    }

    fun getTsName(): String {
        return getIndexName()
    }

    fun getTsUrl(): String? {
        return url
    }


    private fun getSuffixName(name: String): String {
        if (TextUtils.isEmpty(name)) {
            return ""
        }
        val dotIndex = name.lastIndexOf('.')
        return if (dotIndex >= 0) name.substring(dotIndex) else ""
    }

    fun getIndexName(): String {
        var suffixName = ""
        if (!TextUtils.isEmpty(url)) {
            val uri = Uri.parse(url)
            var fileName = uri.lastPathSegment
            if (!TextUtils.isEmpty(fileName)) {
                fileName = fileName!!.lowercase(Locale.getDefault())
                suffixName = getSuffixName(fileName)
            }
        }
        return "video_$index$suffixName"
    }
}